import IconFont from "@/components/IconFont";
import {
	ClipboardText,
	CommonText,
	DownTime,
	NumText,
	StatusText
} from "@/pages/OrderModule/common/components/CommonText";
import { OrderDownTime } from '@/pages/OrderModule/common/components/CommonText/components/OrderDownTime'
import Typography from "@/pages/OrderModule/common/components/Typography";
import { formatTime } from "@/pages/OrderModule/common/utils/time";
import { Space, Popover } from "antd";
import { COLLECT, ORDER_STATUS } from "../../../../../../common/utils/map.js";
import ShopIcons from "@/views/components/ShopIcons";
import { getCellRenderComp } from '../CellRender/index.jsx';
import styles from "./index.module.less";

//旗帜映射
const flagConfig = {
	0: "无旗",
	1: <IconFont type="iconqizhihong" />,
	2: <IconFont type="iconqizhihuang" />,
	3: <IconFont type="iconqizhilv" />,
	4: <IconFont type="iconqizhilan" />,
	5: <IconFont type="iconqizhizi" />
}

const renderBuyerNickName = (val) => {
	const { orderChannel, buyerNickName } = val;
	if (!buyerNickName) {
		return '-';
	} else if (orderChannel == 4 || orderChannel == 8) {
		if (buyerNickName?.startsWith('AA') && buyerNickName?.length >= 24) {
			return (
				<span
					className="J_WangWang"
					data-nick={buyerNickName}
					data-icon="small"
					data-from="taobao"
					data-encryptuid={buyerNickName}
					data-bizdomain="taobao"
					data-appkey="23416550"
					data-biztype={1}
					data-sceneparam={JSON.stringify({ toRole: 'buyer', bizRef: '' })}
					data-encode={true}
				>
					{buyerNickName}
				</span>
			);
		}
		return (
			<a
				style={{ color: '#00a8ec' }}
				href={`https://amos.alicdn.com/getcid.aw?v=3&site=cntaobao&groupid=0&s=1&fromid=&uid=${buyerNickName}&status=1&charset=utf-8`}
				target="_blank"
			>
				<IconFont style={{ marginRight: '4px' }} type="iconwangwang" />
				{buyerNickName}
			</a>
		);
	} else {
		return buyerNickName;
	}
};

//字段配置列
const columnsConfig = {
	'dataIndex': {
		title: "序号",
		code: "dataIndex",
		lock: true,
		width: 60,
		render(v, r, i) {
			return i + 1;
		}
	},
	'sn': {
		title: '系统订单号',
		code: 'sn',
		width: 150,
	},
	'labelList': {
		title: '订单标签',
		code: 'labelList',
		width: 120,
	},
	'goodsList': {
		title: '商品',
		code: 'goodsList',
		width: 300,
	},
	'outOrderSn': {
		title: '店铺订单号',
		code: 'outOrderSn',
		width: 180,
		render(v, r) {
			const outOrderSn = new Set(r['goodsList']?.map(k => k['outOrderSn']).filter(Boolean) || []);
			return (
				<Space>
					{[...outOrderSn.values()].map((k, i) => (
						<ClipboardText key={i} as="s1" text={k} />
					))}
				</Space>
			);
		}
	},
	'printState': {
		title: '快递单打印',
		code: 'printState',
		width: 120,
		render: (t, r) => {
			if(t == 0) {
				return '未打印';
			} else {
				return '已打印';
			}
		}
	},
	'printBatchNumber': {
		title: '打印批次',
		code: 'printBatchNumber',
		width: 120,
		render: t => {
			return (
				t.map(v => {
					return (
						<div key={v}>{v}</div>
					)
				})
			)
		}
	},
    'shippingNotePrintState': {
		title: '发货单打印',
		code: 'shippingNotePrintState',
		width: 120,
		render: (t, r) => {
			if (t == 1) {
				return '已打印';
			} else {
				return '未打印';
			}
		}
	},
	'buyerAccount': {
		title: '买家账号',
		code: 'buyerNickName',
		width: 150,
		render: (t, r) => {
			return (<>{renderBuyerNickName(r)}</>)
		}
	},
	'ecStoreName': {
		title: '店铺',
		code: 'ecStoreName',
		width: 230,
		render(v, r) {
			return (
				<CommonText
					icon={v ? <ShopIcons type={r['orderChannel']} /> : null}
					as="s1"
					text={v ? v : "--"}
				/>
			);
		}
	},
	'totalAmount': {
		title: '采购额',
		code: 'totalAmount',
		width: 120,
		render(v, r) {
			const amountConfig = [
				{ title: '（商品）', value: 'goodsAmount'},
				{ title: '（包材费）', value: 'packAmount'},
				{ title: '（服务费）', value: 'payServiceFee'},
				{ title: '（预估运费）', value: 'estimateFreightAmount'},
				{ title: '（实际运费）', value: 'logisticsRealFee'},
			]
			return (
				<Popover
					placement="bottom"
					content={
						<Space direction="vertical" size={4}>
							<NumText type="error" as="s1" pre={v ? "¥ " : ""} useBold num={v} />
							{
								amountConfig.map(item => (
									<NumText
										as="s1"
										key={item.value}
										pre={r[item.value] ? "¥" : ""}
										num={r[item.value] || 0}
										suffix={item.title}
									/>
								))
							}
						</Space>
					}
					arrow
				>
					<NumText type="error" as="s1" pre={v ? "¥ " : ""} num={v} useBold />
				</Popover>
			);
		}
	},
	'totalGoodsNum': {
		title: '货品总数',
		code: 'totalGoodsNum',
		width: 120,
		render(v) {
			return <NumText as="s1" num={v} />;
		}
	},
	'skuTotal': {
		title: '货品种类',
		code: 'skuTotal',
		width: 120,
		render(v) {
			return <NumText as="s1" num={v} />;
		}
	},
	'ecActualPayment': {
		title: '平台实付金额',
		code: 'ecActualPayment',
		width: 120,
		render(v) {
			return <NumText as="s1" pre={v ? "¥" : ""} num={v} />;
		}
	},
	'payState': {
		title: '支付状态',
		code: 'payState',
		width: 120,
	},
	'state': {
		title: '订单状态',
		code: 'state',
		width: 120,
		getCellProps(value, { state }, rowIndex) {
			const orderState = {
				10: "#FFD1A3",
				20: "#99C3FF",
				30: "#F9B1A9",
				40: "#99E4C8",
				50: "#E0E2E7",
				51: "#E0E2E7",
				52: "#E0E2E7",
			}
			return {
				style: { background: orderState[state] },
			}
		},
		render(v, r) {
			const orderState = {
				10: "warning",
				20: "warning",
				30: "error",
				40: "success",
				50: "info",
				51: "info",
				52: "info",
			}
			return (
				<Space direction="vertical" size={2}>
					<StatusText
						as="s1"
						text={ORDER_STATUS[r.state]}
						type={orderState[r.state]}
					/>
					{r['state'] === 30 && (
						<span as="s1" style={{color: "#15263A"}}>
							{r['errorInfoList'][0]?.errorName}
						</span>
					)}
				</Space>
			);
		}
	},
	'errorInfoList': {
		title: '异常处理意见',
		code: 'errorInfoList',
		width: 120,
		render(v) {
			return v?.map((k, i) => {
				const descList = k.proposal.split('/n');
				return (
					<div key={i}>
						{k.errorDesc}
						{descList.map(item => <p key={item}>{item}</p>)}
					</div>
				)
			});
		}
	},
	'warehouseOrderState': {
		title: '仓库状态',
		code: 'warehouseOrderState',
		width: 120,
		render(v) {
			return <span>{COLLECT[v] || null}</span>;
		}
	},
	'warehouseName': {
		title: '发货仓',
		code: 'warehouseName',
		width: 150,
	},
	'logisticsList': {
		title: '快递',
		code: 'logisticsList',
		width: 180,
	},
	'estimateFreightAmount': {
		title: (
			<>
				<Typography as="s2" useBold>
					预估运费
				</Typography>
				<Popover
					placement="top"
					content={<>注释：该运费是根据运费模板计算的运费<br />实际是否需要支付由订单类型决定</>}
					overlayClassName={styles.goods_pop}
				>
					<span className={styles.goods_icon}>
						<IconFont type="iconwenhao1" />
					</span>
				</Popover>
			</>
		),
		code: 'estimateFreightAmount',
		width: 120,
		render(v) {
			return <NumText as="s1" pre={v ? "¥" : ""} num={v || 0} />
		}
	},
	'noLogisticsList': {
		title: '平台禁发快递公司',
		code: 'noLogisticsList',
		width: 150,
		render(v) {
			return v?.map((k, i) => <span key={i}>{k.expressName}</span>);
		}
	},
	'buyerMessage': {
		title: '买家留言',
		code: 'buyerMessage',
		width: 120
	},
	'flag': {
		title: '旗帜',
		code: 'flag',
		width: 120,
		render(v) {
			return v?.map((k, i) => {
				return (
					<span key={i}>{flagConfig[k]}</span>
				);
			});
		}
	},
	'sellerMessage': {
		title: '卖家备注',
		code: 'sellerMessage',
		width: 120,
	},
	'orderRemark': {
		title: '订单备注',
		code: 'orderRemark',
		width: 120,
	},
	'ecLastDeliveryTime': {
		title: '平台最晚发货时间',
		code: 'ecLastDeliveryTime',
		width: 160,
		render(v, record) {
			return (
				<Space size={2}>
					{formatTime(v)}
					<OrderDownTime
						as="s1"
						time={v}
						record={record}
						renderOverTime={t => (
							<Typography type="error" as="s1">
								已超过（{t}）
							</Typography>
						)}
						renderBeforeTime={t => <Typography as="s1">剩余时间：{t}</Typography>}
					/>
				</Space>
			);
		}
	},
	'deliveryInfoList': {
		title: '收件信息',
		code: 'deliveryInfoList',
		width: 260,
	},
	'totalWeight': {
		title: '重量',
		code: 'totalWeight',
		width: 100,
		render(v) {
			return <NumText as="s1" suffix={v ? "kg" : ""} num={v} />;
		}
	},
	'deliveryTime': {
		title: '发货时间',
		code: 'deliveryTime',
		width: 150,
		render(v, r) {
			return formatTime(r.logisticsList[0]?.deliveryTime);
		}
	},
	'sysGoodsRemark': {
		title: '商品备注',
		code: 'sysGoodsRemark',
		width: 150,
		render(v, r) {
			return (
				r.goodsList
					.map(el => el.sysGoodsRemark)
					.filter(Boolean)
					.join()
			);
		}
	},
	'payTime': {
		title: '系统支付时间',
		code: 'payTime',
		width: 150,
		render(v) {
			return formatTime(v);
		}
	},
	'ecPayTime': {
		title: '平台付款时间',
		code: 'ecPayTime',
		width: 150,
		render(v) {
			return formatTime(v);
		}
	}
}

//获取当前的列函数
export const getColumnsData = (props) => {
	const { columns } = props;
	const customRender = getCellRenderComp(props);
	const arr = [];
	for (let i in columns) {
		const obj = columns[i];
		const item = columnsConfig[obj.code];
		const customRenderData = customRender[obj.code];
		//单独的title渲染和render函数渲染
		if (customRenderData) {
			customRenderData.title && (item.title = customRenderData.title());
			customRenderData.render && (item.render = customRenderData.render);
		}
		if (obj.checked && item) {
			arr.push({
				...item,
				width: obj.width,
				lock: obj.lock
			})
		}
	}
	return arr;
}